package com.xxx.base.spring;

import com.xxx.base.util.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 方法执行监控切面
 */
@Component
@Aspect
public class MonitorAspect {
    protected final Log log = Log.of(getClass());

    @Pointcut("@annotation(com.xxx.base.spring.Monitor)")
    public void pointCut() {}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Monitor anno = signature.getMethod().getAnnotation(Monitor.class);

        long start = System.currentTimeMillis();
        Throwable ex = null;
        Object ret = null;
        try {
            ret = pjp.proceed();
        } catch (Throwable t) {ex = t;}
        long end = System.currentTimeMillis();

        boolean warn = (end - start >= anno.warnTimeUnit().toMillis(anno.warnTimeOut()));
        if (anno.trace() || warn) {
            StringBuilder sb = new StringBuilder(anno.logPrefix());
            Method m = signature.getMethod();
            // sb.append(signature.toShortString());
            sb.append(m.getDeclaringClass().getName()).append(".").append(m.getName());
            Object[] args = pjp.getArgs();
            if (anno.printArgs() && args.length > 0) {
                sb.append("(");
                for (int i = 0; i < args.length; i++) {
                    if (i == 0) sb.append(Objects.toString(args[i], "null"));
                    else sb.append(";").append(Objects.toString(args[i], "null"));
                }
                sb.append(")");
            }
            sb.append(", time: ").append(end - start).append("ms");
            if (warn) log.warn(sb.append(anno.logSuffix()).toString());
            else log.info(sb.append(anno.logSuffix()).toString());
        }

        if (ex != null) throw ex;
        return ret;
    }
}
